
package org.linlinjava.litemall.wx.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.catalina.manager.HTMLManagerServlet;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.linlinjava.litemall.core.config.WxProperties;
import org.linlinjava.litemall.wx.dto.WxBaseLoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriComponentsBuilder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@EnableConfigurationProperties(WxProperties.class)
public class WxDecrypt {
    // 微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    private WxProperties wxProperties;

    public WxDecrypt(WxProperties wxProperties) {
        this.wxProperties = wxProperties;
    }
    public String getOpenid(String loginCode){
        String appId = this.wxProperties.getAppId();
        String secret =  this.wxProperties.getAppSecret();
        Map<String, String> map = new HashMap<>();
        map.put("appid", appId);
        map.put("secret", secret);
        map.put("js_code", loginCode);
        map.put("grant_type", "authorization_code");
        // 发送请求

        String json = HttpClientUtil.doGet(WX_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(json);
        return jsonObject.getString("openid");
    }
    public String getAccessToken() {
        String appId = this.wxProperties.getAppId();
        String secret =  this.wxProperties.getAppSecret();
        // 使用 UriComponentsBuilder 构造 URL
        URI uri = UriComponentsBuilder.fromHttpUrl("https://api.weixin.qq.com/cgi-bin/token")
                .queryParam("appid", appId)
                .queryParam("secret", secret)
                .queryParam("grant_type", "client_credential")
                .build().toUri();

        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(new HttpGet(uri))) {

            String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            JSONObject jsonResponse = JSONObject.parseObject(responseBody);
            return jsonResponse.getString("access_token");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getPhoneInfo(String accessToken, String code) {
        // 使用 UriComponentsBuilder 构造 URL
        URI uri = UriComponentsBuilder.fromHttpUrl("https://api.weixin.qq.com/wxa/business/getuserphonenumber")
                .queryParam("access_token", accessToken)
                .build().toUri();

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(uri);
            JSONObject requestBody = new JSONObject();
            requestBody.put("code", code);

            httpPost.setEntity(new StringEntity(requestBody.toJSONString(), StandardCharsets.UTF_8));
            httpPost.setHeader("Content-Type", "application/json");

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                JSONObject jsonResponse = JSONObject.parseObject(responseBody);

                if (jsonResponse.getIntValue("errcode") == 0) {
                    return jsonResponse.getString("phone_info");
                } else {
                    System.err.println("获取手机号失败: " + jsonResponse.getString("errmsg"));
                    return null;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}